﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Out2Share
{
    /// <summary>
    /// Thread used to upload file in Sharepoint
    /// </summary>
    public class UploadThread
    {
        TreeViewContainer treeview;
        string[] filenames;
        MemoryStream[] filestreams;
        string site;
        string library;
        ConfData conf;
        string currentFolder;

        public UploadThread(TreeViewContainer _treeview, string[] _filenames, MemoryStream[] _filestreams, ConfData _conf, string _site,string _library, string _currentFolder)
        {
            treeview = _treeview;
            filenames = _filenames;
            filestreams = _filestreams;
            site = _site;
            library = _library;
            conf = _conf;
            currentFolder = _currentFolder;
        }

        public void Run() {
            try
            {
                for (int fileIndex = 0; fileIndex < filenames.Length; fileIndex++)
                {
                    OutlookStorage.Message message = new OutlookStorage.Message(filestreams[fileIndex]);
                    if (message.BodyText == null)
                    {
                        string fileNameUp = filenames[fileIndex];
                        SharepointHelper.UploadFile(conf, site, library, "", "", "", DateTime.Now, fileNameUp, currentFolder, filestreams[fileIndex].ToArray());
                    }
                    else
                    {
                        string to = "";
                        foreach (OutlookStorage.Recipient rec in message.Recipients)
                        {
                            if (to != "") to = to + ";";
                            to = to + rec.DisplayName;
                        }
                        string fileNameUp = message.Date.ToString("G") + "-" + message.Subject + ".msg";
                        SharepointHelper.UploadFile(conf, site, library, message.Subject, message.From, to, message.Date, fileNameUp, currentFolder, filestreams[fileIndex].ToArray());
                    }
                }
                treeview.Invoke(treeview.uploadDelegate,
                                   new Object[] { filenames.Length });
            }
            catch (Exception e) {
                treeview.Invoke(treeview.ErrorOnThreadDelegate,
                                      new Object[] { e.Message });
            }
        }
    }
}
